<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNumber">
        <el-input v-model="queryParams.orderNumber" placeholder="请输入订单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="计划名称" prop="progName">
        <el-input v-model="queryParams.progName" placeholder="请输入计划名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="proName">
        <el-input v-model="queryParams.proName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">


      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['mes:plan:export']">导 出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderNumber" />
      <el-table-column label="产品名称" align="center" prop="proName" />
      <el-table-column label="生产计划编号" align="center" prop="progCode" />
      <el-table-column label="计划数量" align="center" prop="progQuantity" />

      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="mingxi(scope.row.id)"
            v-hasPermi="['mes:plan:edit']">计划明细</el-button>

          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click=""
            v-hasPermi="['mes:plan:remove']">撤回</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />




    <!-- 计划明细 -->
    <el-drawer size="60%" title="计划明细" :visible.sync="planchoose" v-if="planchoose">
      <div style="display: flex;background-color:#939faeba;border-radius: 10px;margin: 10px;">
        <el-card id="planchanpincard" shadow="hover">
          <el-tag style="display: block;text-align: center;" effect="plain">
            产品名称
          </el-tag>
          <el-divider></el-divider>
          <label style="display: block; text-align: center;">{{ planprodata.proInfo.proName }}</label>
        </el-card>


        <el-card id="planchanpincard" shadow="hover">
          <el-tag style="display: block;text-align: center;" effect="plain">
            产品编码
          </el-tag>
          <el-divider></el-divider>
          <label style="display: block; text-align: center;">{{ planprodata.proInfo.proCode }}</label>
        </el-card>

        <el-card id="planchanpincard" shadow="hover">
          <el-tag style="display: block;text-align: center;" effect="plain">
            计划数量
          </el-tag>
          <el-divider></el-divider>
          <label style="display: block; text-align: center;">{{ planprodata.progPlan.progQuantity }}</label>
        </el-card>

        <el-card id="planchanpincard" shadow="hover">
          <el-tag style="display: block;text-align: center;" effect="plain">
            还需下达数
          </el-tag>
          <el-divider></el-divider>
          <label style="display: block; text-align: center;">{{
            planprodata.progPlan.progQuantity - releasedQuantitysum < 0 ? 0 : planprodata.progPlan.progQuantity -
            releasedQuantitysum }}</label>
        </el-card>

        <el-card id="planchanpincard" shadow="hover">
          <el-tag style="display: block;text-align: center;" effect="plain">
            已下达数量
          </el-tag>
          <el-divider></el-divider>
          <label style="display: block; text-align: center;">{{ releasedQuantitysum }}</label>
        </el-card>
      </div>

      <el-divider></el-divider>

      <el-card
        style="width: 98%;margin: auto;margin-top: 20px;background-color: rgba(175, 197, 192, 0.717);border-radius: 10px;border: unset; "
        class="box-card">
        <div slot="header" class="clearfix">
          <span>计划下达</span>
        </div>
        <div>
          <el-table id="plantable" :data="planDeatils" border style="width: 100%;border-radius: 10px;" empty-text="1">
            <el-table-column prop="status" align="center" label="计划状态">
              <template slot-scope="scope">
                <el-tag :type="tagType(scope.row.status)" effect="dark">
                  <dict-tag :options="dict.type.mes_progplan_status" :value="scope.row.status" />
                </el-tag>

              </template>
            </el-table-column>
            <el-table-column prop="releaseQuantity" align="center" label="下达数量">
            </el-table-column>
            <el-table-column prop="startTime" align="center" label="计划开始日期">
            </el-table-column>
            <el-table-column prop="overTime" align="center" label="计划结束日期">
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button v-if="scope.row.status == 1" size="mini" type="text" icon="el-icon-delete"
                  @click="chehui(scope.row)" v-hasPermi="['mes:plan:remove']">撤回</el-button>
              </template>
            </el-table-column>
            <div slot="append">
              <el-form ref="form" style="display: flex;" :model="xiadadata" :rules="rules">
                <span style="flex: 1;text-align: center;padding-top: 5px;">未下达</span>
                <el-input-number style="flex: 1;" v-model="xiadadata.releaseQuantity" controls-position="right"
                  :min="0"></el-input-number>
                <el-date-picker style="flex: 1;" v-model="xiadadata.startTime" type="date" placeholder="选择开始日期"
                  format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
                </el-date-picker>
                <el-date-picker style="flex: 1;" v-model="xiadadata.overTime" type="date" placeholder="选择结束日期"
                  format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
                </el-date-picker>
                <div style="flex: 1;text-align: center;">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="xiada"
                    v-hasPermi="['mes:plan:edit']">下达</el-button>
                </div>
              </el-form>
            </div>
          </el-table>
        </div>
      </el-card>
    </el-drawer>


  </div>
</template>

<script>
import { listPlan, getPlan, delPlan, addPlan, updatePlan, release, planDeatils, getplanList, revokeProgPlanDetails } from "@/api/mes/plan";

export default {
  name: "Plan",
  dicts: ['mes_pro_type', 'mes_progplan_status'],
  data() {
    return {
      //已下达数量
      releasedQuantitysum: 0,
      //计划下达中
      planing: false,
      //下达行的数据
      xiadadata: {},
      //计划明细计划数据
      planDeatils: [],
      //计划明细产品数据
      planprodata: [],

      //作废
      timeform: {
        //计划结束时间
        overTime: "",
        //计划开始时间
        startTime: "",

      },
      nowid: "",
      //计划明细对话框
      planchoose: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: null,
        progName: null,
        taskCardId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        overTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //标签类型判断
    tagType(status) {
      switch (status) {
        case 0:
          return "danger"
        case 1:
          return "success"
      }
    },
    /**
     * 撤回
     */
    chehui(row) {
      revokeProgPlanDetails({ id: row.id }).then(res => {
        this.$notify({
          title: '成功',
          message: '计划撤回成功',
          type: 'success',
          position: 'top-left'
        });
        this.mingxi(this.nowid)
      })
    },
    /**
     * 下达事件
     */
    xiada() {
      //时间判断
      if (this.xiadadata.startTime == null || this.xiadadata.overTime == null) {
        this.$modal.msgError("请填写开始时间或结束时间！");
      } else if (new Date(this.xiadadata.startTime) > new Date(this.xiadadata.overTime)) {
        this.$modal.msgError("开始时间超过结束时间！");
      }
      else {
        const loading = this.$loading({
          lock: true,
          text: '计划下达中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        release({
          id: this.nowid, releaseQuantity: this.xiadadata.releaseQuantity, startTime: this.xiadadata.startTime, overTime: this.xiadadata.overTime
        }).then(() => {
          setTimeout(() => {
            loading.close();
            this.$notify({
              title: '成功',
              message: '计划下达成功！',
              type: 'success',
              position: 'top-left'
            });
            // this.$modal.msgSuccess("计划下达成功！");
            this.mingxi(this.nowid)
          }, 1000);
        })
      }


    },

    /**
     * 计划明细
     */
    mingxi(id) {
      //获取当前点击的生产计划id
      this.nowid = id;
      //已下达数量重置
      this.releasedQuantitysum = 0
      //将用户需填写的下达行清空
      this.xiadadata = {
        id: null,
        releaseQuantity: 0,
        startTime: null,
        overTime: null,
      }
      //计划明细产品信息
      planDeatils({ id: id }).then((res) => {
        this.planprodata = res.data
      })
      //计划明细计划信息
      getplanList({ progId: id }).then(res => {
        this.planDeatils = res.data
        console.log("🚀 ~ file: index.vue:313 ~ getplanList ~ this.planDeatils = res.data:", this.planDeatils = res.data)
        // 打开抽屉
        this.planchoose = true;
        //计算已下达数量
        this.planDeatils.forEach(element => {
          if (element.status == 1) {
            this.releasedQuantitysum += element.releaseQuantity
          }
        });
      })

    },
    /** 查询生产计划列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderNumber: null,
        progName: null,
        proName: null,
        progQuantity: null,
        proType: null,
        progCode: null,
        startTime: null,
        overTime: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPlan(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改生产计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePlan(this.form).then(response => {
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                position: 'top-left'
              });
              // this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlan(this.form).then(response => {
              this.$notify({
                title: '成功',
                message: '新增成功',
                type: 'success',
                position: 'top-left'
              });
              // this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除生产计划编号为"' + ids + '"的数据项？').then(function () {
        return delPlan(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
/deep/ .el-divider--horizontal {
  margin: 10px;
  width: unset;
}

#planchanpincard {
  flex: 1;
  background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);
  margin: 10px;
  border-radius: 10px;
}

/deep/ .el-drawer {
  background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 10px;
}

/deep/.el-drawer__header {
  margin-bottom: unset;
}

#plantable>>>.el-table__empty-block {
  height: 0px !important;
  min-height: unset
}
</style>